/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package spendreport.java.examples;

import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.walkthrough.common.entity.Alert;
import org.apache.flink.walkthrough.common.entity.Transaction;
import org.apache.flink.walkthrough.common.sink.AlertSink;
import org.apache.flink.walkthrough.common.source.TransactionSource;

/**
 * Skeleton code for the datastream walkthrough
 * 		定义了程序的数据流
 *
 * @author huanghaifeng15
 */
public class FraudDetectionJob {

	public static void main(String[] args) throws Exception {
		// 设置执行环境，用于定义任务的属性、创建数据源以及最终启动任务的执行
		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

		// 创建数据源；从外部系统获取数据输入，输入到Flink程序中。
		// 每条交易数据都包含一个模型Transaction，绑定数据源上的name属性，为了方便调试。
		DataStream<Transaction> transactions = env
			.addSource(new TransactionSource())
			.name("transactions");

		// transactions 的这个数据流上包含有大量的用户交易信息
		// 一个欺诈行为的发生是基于某一个账户的。所以，必须保证同一个账号的所有交易记录是要被同一个并发的task进行处理。
		// 将多个账户的数据发送到并发上进行欺诈检测处理
		DataStream<Alert> alerts = transactions
				// 对流根据账户ID进行分区
			.keyBy(Transaction::getAccountId)
				// 对流绑定了一个操作
			.process(new FraudDetector())
				// 定义name属性
			.name("fraud-detector");

		// sink 会将 DataStream 写出到外部系统。
		alerts
				// AlertSink 使用INFO级别日志打印每一个Alter数据，而不是持久化存储。
			.addSink(new AlertSink())
			.name("send-alerts");

		// 运行作业
		env.execute("Fraud Detection");
	}
}
